import React, { useState, useEffect, useMemo, useRef } from 'react';
import { useParams, useSearchParams } from 'react-router-dom';
import { Tag, Loading } from '@block/plug';
import { RiskLevel, getUUid } from '@src/utils';
import { $fetch, isH5Mobile } from '@block/utils';
import { UnusualPage } from '@src/components';

import { AuditLevelModal, RiskLevelModal, ReportPc, ReportMobile, FindingsDrawer } from './elements/index';
import { ReportPreview, AuditProblemListType, RiskImgData, LevelTableRow, BizOpType, OpLogData } from './type';
import './index.scss';
import Url from './url';

/**
 * 项目报告预览
 */

const ProjectReportPreview = () => {
  const urlParams = useParams<{ id: string }>();
  const [searchParams] = useSearchParams();

  const [loading, setLoading] = useState(false);
  const [reportData, setReportData] = useState<ReportPreview>(null);
  const [auditVisible, setAuditVisible] = useState(false);
  const [riskVisible, setRiskVisible] = useState(false);
  const [findingsVisible, setFindingsVisible] = useState(false);
  const [riskImg, setModalImg] = useState<RiskImgData>(null);
  const [levelTable, setLevelTable] = useState<LevelTableRow[]>([]);
  /** 审计发现传递行信息 */
  const [findingsRowData, setFindingsRowData] = useState<AuditProblemListType>();
  /** 租户ID */
  const tenantId = searchParams.get('tenantId') || window.localStorage.getItem('tenantId') || 'MT_INTERNAL_AUDIT';
  /** 无权限时显示页面 */
  const [permissionsPage, setPermissionsPage] = useState(false);

  const traceId = useRef<string>(getUUid('string') as string);

  /** 项目编号 */
  const itemNo = useMemo(() => {
    return urlParams?.id;
  }, [urlParams?.id]);

  /**
   * 页面访问数据上报
   * @param bizOpType 事件类别
   * @param params 参数
   */
  const handleMonitor = async (bizOpType: BizOpType, params?: OpLogData) => {
    try {
      await $fetch(Url.addOperateLog, {
        tenantId,
        itemNo,
        bizOpType,
        opLogData: { traceId: traceId.current, deviceType: isH5Mobile() ? 'MOBILE' : 'COMPUTER', ...params },
      });
    } catch (e) {
      console.warn(e);
    }
  };

  /**
   * 审计项目报告预览
   */
  const handleInitList = async () => {
    setLoading(true);
    try {
      const res = await $fetch<ReportPreview>(Url.getPreviewDetail, { itemNo, tenantId });
      let num = 0;
      const data = {
        ...res,
        auditProblemDetailList: res.auditProblemDetailList?.map((item) => {
          return {
            ...item,
            auditProblemList: item.auditProblemList?.map((child) => {
              num += 1;
              return {
                ...child,
                indexCode: num,
              };
            }),
          };
        }),
      };
      handleMonitor(BizOpType.openPageSuccess);
      setReportData(data);
    } catch (error) {
      if (error?.errorCode === 10001) {
        setPermissionsPage(true);
      }
      throw error;
    } finally {
      setLoading(false);
    }
  };

  const handleModalRes = async () => {
    const res = await $fetch<RiskImgData>(Url.queryRiskLevelPicUrl, { pageVersion: reportData?.pageVersion });
    if (res) {
      setModalImg(res);
    }
  };

  const handleLevelTableList = async () => {
    const res = await $fetch(Url.queryReportLevelDesc);
    if (res) {
      setLevelTable(res);
    }
  };

  useEffect(() => {
    handleInitList();
    handleModalRes();
    handleLevelTableList();
    handleMonitor(BizOpType.openPAge);

    return () => {
      handleMonitor(BizOpType.closePage);
    };
  }, []);

  const handleCloseAuditModel = () => {
    setAuditVisible(false);
  };
  const handleCloseRiskModel = () => {
    setRiskVisible(false);
  };
  const handleCloseFindingsDrawer = () => {
    setFindingsVisible(false);
  };
  const handleOpenAuditModel = () => {
    setAuditVisible(true);
  };
  const handleOpenRiskModel = () => {
    setRiskVisible(true);
  };
  const handleOpenFindingsDrawer = (row: AuditProblemListType) => {
    setFindingsRowData(row);
    setFindingsVisible(true);
  };

  const getContainer = (): HTMLElement => {
    return document.querySelector('.project-report-preview-content') || document.body;
  };

  /** 风险等级判定 */
  const renderRiskLevel = (riskLevel: string, riskLevelName: string, tagStyle: boolean) => {
    switch (riskLevel) {
      case RiskLevel.high:
        return (
          <Tag theme="red" type={tagStyle ? 'bordered' : 'text'}>
            {riskLevelName}
          </Tag>
        );
      case RiskLevel.medium:
        return (
          <Tag theme="orange" type={tagStyle ? 'bordered' : 'text'}>
            {riskLevelName}
          </Tag>
        );
      case RiskLevel.low:
        return (
          <Tag theme="green" type={tagStyle ? 'bordered' : 'text'}>
            {riskLevelName}
          </Tag>
        );
      default:
        return null;
    }
  };

  return (
    <>
      {permissionsPage ? (
        <UnusualPage tips="暂无浏览权限" detail="还没有浏览权限，联系下管理员吧！" type="noPermission" />
      ) : (
        <div className="project-report-preview-wrap">
          <Loading loading={loading} className="project-report-loading">
            {isH5Mobile() ? (
              <ReportMobile
                handleMonitor={handleMonitor}
                reportData={reportData}
                handleOpenAuditModel={handleOpenAuditModel}
                handleOpenRiskModel={handleOpenRiskModel}
              />
            ) : (
              <ReportPc
                handleMonitor={handleMonitor}
                reportData={reportData}
                handleOpenAuditModel={handleOpenAuditModel}
                handleOpenRiskModel={handleOpenRiskModel}
                renderRiskLevel={renderRiskLevel}
                handleOpenFindingsDrawer={handleOpenFindingsDrawer}
                getContainer={getContainer}
              />
            )}
            {findingsVisible && (
              <FindingsDrawer
                reportData={reportData}
                findingsRowData={findingsRowData}
                onClose={handleCloseFindingsDrawer}
              />
            )}
            {auditVisible && <AuditLevelModal levelTable={levelTable} onClose={handleCloseAuditModel} />}
            {riskVisible && <RiskLevelModal riskImg={riskImg} onClose={handleCloseRiskModel} />}
          </Loading>
        </div>
      )}
    </>
  );
};
export default ProjectReportPreview;
